package controller;

import dao.UserInfoDao;
import dao.impl.UserInfoDaoImpl;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author ：Teacher陈（86521760@qq.com）
 * @date ：Created in 2022/3/23 9:32
 * @description：登录控制器
 * @modified By：
 * @version: 1.0
 */
@WebServlet(urlPatterns = "/login")
public class LoginServlet  extends HttpServlet {
    UserInfoDao userInfoDao= new UserInfoDaoImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      /*  //获取上下文
        ServletContext servletContext = getServletContext();
        //获取全局配置
        String encode = servletContext.getInitParameter("encode");
        //设置编码格式
        req.setCharacterEncoding(encode);
        resp.setContentType("text/html;charset=utf-8");
        resp.setCharacterEncoding(encode);*/
       //业务逻辑
        System.out.println("登录控制器开始工作了");
        //获取请求参数
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        //将用户名和密码传入到数据库中查询是否正确
        //select * from userinfo where username=?  and password=?
        List<Map<String, Object>> mapList = userInfoDao.findUserInfoByUserNameAndPassword(username, password);
        String  message="";
      /*  if(null!=mapList&&mapList.size()>0){
            //登录成功
            message="登录成功,欢迎"+username;
        }else
        {
            //登录失败
            message="登录失败";
        }

        resp.getWriter().write("<h1>"+message+"</h1>");*/
        //使用转发的方式，进行页面的跳转
        if(null!=mapList&&mapList.size()>0){
            //登录成功，转发到成功的页面
            req.setAttribute("username",username);
            UserInfoDao userInfoDao = new UserInfoDaoImpl();
            List<Map<String, Object>> allUser = userInfoDao.findAllUser();
            req.setAttribute("allUser",allUser);
            req.getRequestDispatcher("success.jsp").forward(req,resp);
        }else
        {
            //登录失败，转发到失败的页面
            req.getRequestDispatcher("fail.jsp").forward(req,resp);
        }
        //使用重定向方式，页面跳转
       /* if(null!=mapList&&mapList.size()>0){
            //登录成功，转发到成功的页面
            //重定向request中的内容会丢失
            //req.setAttribute("username",username);
            //使用session保存用户信息
            HttpSession session = req.getSession();
            session.setAttribute("username",username);
            resp.sendRedirect("success.jsp");
        }else
        {
            //登录失败，转发到失败的页面
            resp.sendRedirect("fail.jsp");
        }*/

    }
}
